<?php
/**
 * 发票处理类
 *
 * @author xiayuanjun<xiayuanjun@shopex.cn>
 * wangjianjun update 20160623
 * @version 0.1
 */
class invoice_process
{
    /**
     * 新增发票记录处理函数
     * @param array $params 传入参数
     */
    public function create($params,$type='auto'){
        
        //order_id是必须的
        $order_id = $params['order_id'];
        if(!$order_id){
            return false;
        }
        
        $check_create = kernel::single('invoice_check')->checkCreate($order_id);
        if(!$check_create){
            return false;
        }
        
        //获取order表信息
        $mdlOmeOrders = app::get('ome')->model('orders');
        $rs_orders = $mdlOmeOrders->dump(array("order_id"=>$order_id));
        if (empty($rs_orders)){
            return false;
        }
        
        //获取前端店铺发票配置信息
        $shop_id = $rs_orders["shop_id"];
        $rs_setting = kernel::single('invoice_common')->getInvoiceOrderSet($shop_id);
        
        $mdlInOrder = app::get('invoice')->model('order');
        
        if($type == 'auto'){
            //前端店铺下单 和 手动新建订单
            if($rs_orders['is_tax'] == 'false'){
                //手动新建订单 不选择开票
                return false;
            }
            $invoice_mode = intval($params['invoice_mode']); //默认0纸质发票 电子发票为1
            $order_bn = $params['order_bn'];
            $tax_rate = $rs_setting["tax_rate"] ? $rs_setting["tax_rate"] : 0;//税率
            $tax_title = strip_tags(trim($params['tax_title'])); //发票抬头
            $content_id = $rs_setting['content_id'] ? $rs_setting['content_id'] : 1; //发票内容 默认为 商品明细
            $consignee_name = $params['consignee']['name']; //收货人名
            $consignee_area = $params['consignee']['area']; //收货人地区
            $consignee_addr = $params['consignee']['addr']; //收货人地址
            $telphone = $params['consignee']['mobile'] ? $params['consignee']['mobile'] : $params['consignee']['telephone']; //电话
            $msg_part = '新订单自动插入发票信息';
        }else if($type == 'order_detail_basic' && $rs_orders["is_tax"] == 'false'){
            //订单明细里“开票”按钮 手动生成 没有发票的订单发票信息
            $invoice_mode = intval($params['invoice_mode']); //默认0纸质发票 电子发票为1
            $order_bn = $rs_orders['order_bn']; //订单号
            $tax_rate = $rs_setting["tax_rate"] ? $rs_setting["tax_rate"] : 0;//税率
            $tax_title = $rs_orders['tax_company']; //发票抬头
            $content_id = $rs_setting['content_id'] ? $rs_setting['content_id'] : 1; //发票内容 默认为 商品明细
            $consignee_name = $rs_orders['ship_name']; //收货人名
            $consignee_area = $rs_orders['ship_area']; //收货人地区
            $consignee_addr = $rs_orders['ship_addr']; //收货人地址
            $telphone = $rs_orders['ship_mobile'] ? $rs_orders['ship_mobile'] : $rs_orders['ship_tel']; //电话
            $msg_part = '手动插入发票信息';
        }else if($type == 'invoice_list_add_same'){
            //获取编辑表单其他的填写数据
            $other_insert = array(
                "remarks" => $params["remarks"],
                "ship_bank" => $params["ship_bank"],
                "ship_bank_no" => $params["ship_bank_no"],
                "ship_tax" => $params["ship_tax"],
            );
            //发票列表 新建发票信息
            $invoice_mode = intval($params['mode']); //默认0纸质发票 电子发票为1
            //获取原发票记录
            $old_invoice_order = $mdlInOrder->dump(array("id"=>$params["id"]));
            $order_bn = $old_invoice_order["order_bn"]; //订单号
            if($invoice_mode == 0){
                //纸质发票金额
                $invoice_amount = number_format($params["amount"],2,".",""); //纸质发票直接取填的开票金额为开票金额
                $other_insert["type_id"] = $params["type_id"];
            }
            $tax_rate = 0;
            if(is_numeric($params["tax_rate"]) && intval($params["tax_rate"]) > 0 ){
                $tax_rate = $params["tax_rate"];
            }
            $tax_title = $params["title"];
            $content_id = $params["content_id"];
            $consignee_name = $params["tax_company"] ? $params["tax_company"] : $rs_orders['ship_name'];
            $consignee_area = $params["ship_area"] ? $params["ship_area"] : $rs_orders['ship_area'];
            $consignee_addr = $params["ship_addr"] ? $params["ship_addr"] : $rs_orders['ship_addr'];
            $telphone = $params['ship_tel'] ? $params['ship_tel'] : $rs_orders['ship_mobile']; //先看表单上是否有填写客户电话
            $telphone = $telphone ? $telphone : $rs_orders['ship_tel']; //电话
            //开票方信息取表单填写 重写rs_setting数组拿input框中的值
            $rs_setting = array(
                "payee_name" => $params['payee_name'],
                "tax_no" => $params['tax_no'],
                "address" => $params['address'],
                "telephone" => $params['telephone'],
                "payee_operator" => $params['payee_operator'],
                "bank" => $params['bank'],
                "bank_no" => $params['bank_no'],
            );
            $msg_part = "新建类似发票信息";
        }
        
        $total_amount = number_format($rs_orders['total_amount'],2,".",""); //订单总金额
        $cost_tax = number_format(($total_amount*$tax_rate)/100,2,".","");//计算税金
        $tax_title = $tax_title ? $tax_title : $consignee_name;//如抬头为空则用收货人名
        $operator = kernel::single('desktop_user')->get_id();//操作人ID
        if(!$invoice_amount){
            $invoice_amount = $total_amount+$cost_tax; //开票金额 (价税合计)
        }
        
        $insert_arr = array(
                'order_id'=>$order_id,
                'order_bn'=>$order_bn,
                'mode' => $invoice_mode,//这个key不存在就是0，1为电子发票
                'amount' => $invoice_amount,
                'cost_tax' => $cost_tax,
                'tax_rate' => $tax_rate,
                'title' => $tax_title,
                'content_id' => $content_id,
                'operator' => $operator,
                'create_time' => time(),
                'tax_company' => $consignee_name,
                'ship_area' => $consignee_area,
                'ship_addr' => $consignee_addr,
                'ship_tel' => $telphone,
                'shop_id' => $shop_id,
                'payee_name' => $rs_setting["payee_name"] ? $rs_setting["payee_name"] : "",
                'tax_no' => $rs_setting["tax_no"] ? $rs_setting["tax_no"] : "",
                'address' => $rs_setting["address"] ? $rs_setting["address"] : "",
                'telephone' => $rs_setting["telephone"] ? $rs_setting["telephone"] : "",
                'payee_operator' => $rs_setting["payee_operator"] ? $rs_setting["payee_operator"] : "",
                'bank' => $rs_setting["bank"] ? $rs_setting["bank"] : "",
                'bank_no' => $rs_setting["bank_no"] ? $rs_setting["bank_no"] : "",
        );
        
        if($other_insert){
            $insert_arr = array_merge($insert_arr,$other_insert);
        }
        
        //新增发票
        $result = $mdlInOrder->insert($insert_arr);
        
        //新增发票日志
        $opObj = app::get('ome')->model('operation_log');
        if($result){
            $msg = $msg_part."成功。";
            $opObj->write_log('invoice_create@invoice', $result, $msg);
            return true;
        }else{
            $msg = $msg_part."失败。";
            $opObj->write_log('invoice_create@invoice', $result, $msg);
            return false;
        }
        
    }

    /**
     * 作废处理函数
     * @param array $params 传入参数
     */
    public function cancel($params,$type='order_cancel'){
        
        $rs_invoice = kernel::single('invoice_check')->checkCancel($params["order_id"]);
        if(!$rs_invoice){
            return false;
        }
        
        //电子发票列表 操作项里的 作废link 必须是同一个id记录 否则返回false
        if($type == 'invoice_list' && intval($rs_invoice["id"]) != intval($params["id"])){
            return false;
        }
        
        $mdlInOrder = app::get('invoice')->model('order');
        
        $operator = kernel::single('desktop_user')->get_id();
        $update_arr = array("is_status"=>2,"update_time"=>time(),"operator"=>$operator);
        $filter_arr = array("id"=>$rs_invoice["id"]);
        
        if(intval($rs_invoice['mode']) == 1){
            //电子发票
            //未开票 并且同步状态是 0(未同步) 和 2(开蓝失败)
            if(intval($rs_invoice['is_status']) == 0 && in_array(intval($rs_invoice['sync']), array(0,2))){
                //直接标记作废
                $result = $mdlInOrder->update($update_arr,$filter_arr);
                $msg_part = "作废未开票电子发票成功。";
            }
            //已开票 并且同步状态是 3(开蓝成功) 4(开红票中) 和 5(冲红失败)
            if(intval($rs_invoice['is_status']) == 1 && in_array(intval($rs_invoice['sync']), array(3,4,5))){
                //电子发票冲红
                $checkEinvoiceCreate = kernel::single('invoice_check')->checkEinvoiceCreate($rs_invoice["id"],"2");
                if(!$checkEinvoiceCreate){
                    return false;
                }
                $rs_invoice = kernel::single('invoice_electronic')->getEinvoiceSerialNo($rs_invoice,"2");
                if(!$rs_invoice){
                    return false;
                }
                //检查必要条件
                $check_do_einvoice = kernel::single('invoice_check')->checkDoEinvoice($rs_invoice);
                if(!empty($check_do_einvoice["arr_hint"])){
                    return $check_do_einvoice;
                }
                kernel::single('invoice_electronic')->do_einvoice_create_limit($rs_invoice["id"],"red"); //做冲红点击动作缓存 防止连续点击
                kernel::single('invoice_event_trigger_einvoice')->cancel($rs_invoice["shop_id"],$rs_invoice);
                return $rs_invoice;
            }
        }else if(intval($rs_invoice['mode']) == 0){
            //纸质发票 直接标记作废
            $result = $mdlInOrder->update($update_arr,$filter_arr);
            $msg_part = "作废纸质发票成功。";
        }
        
        switch ($type){
            case "order_cancel":
                $msg = "订单取消处，".$msg_part;
                break;
            case "invoice_list":
                $msg = "发票列表处，".$msg_part;
                break;
            case "order_detail":
                $msg = "发票详细处是否开票选择否，".$msg_part;
                break;
        }
        
        //记录日志
        $opObj = app::get('ome')->model('operation_log');
        if($result){
            $opObj->write_log('invoice_cancel@invoice', $rs_invoice['id'], $msg);
            return $rs_invoice;
        }
        
    }
    
    /**
     * 开票处理函数
     * @param array $params 传入参数
     */
    function billing($params){
        
        //开票触发点 在发票列表操作区域
        $rs_invoice = kernel::single('invoice_check')->checkBilling($params);
        if(!$rs_invoice){
            return false;
        }
        
        if(intval($rs_invoice["mode"]) == 1){
            //电子发票开蓝
            $checkEinvoiceCreate = kernel::single('invoice_check')->checkEinvoiceCreate($rs_invoice["id"]);
            if(!$checkEinvoiceCreate){
                return false;
            }
            $rs_invoice = kernel::single('invoice_electronic')->getEinvoiceSerialNo($rs_invoice);
            if(!$rs_invoice){
                return false;
            }
            //检查必要条件
            $check_do_einvoice = kernel::single('invoice_check')->checkDoEinvoice($rs_invoice);
            if(!empty($check_do_einvoice["arr_hint"])){
                return $check_do_einvoice;
            }
            kernel::single('invoice_electronic')->do_einvoice_create_limit($rs_invoice["id"]); //做开票点击动作缓存 防止连续点击
            kernel::single('invoice_event_trigger_einvoice')->create($rs_invoice["shop_id"],$rs_invoice);
            return $rs_invoice;
        }else{
            //纸质发票开票
            $mdlInOrder = app::get('invoice')->model('order');
            $cur_time = time();
            $operator = kernel::single('desktop_user')->get_id();
            $update_arr = array("is_status"=>1,"update_time"=>$cur_time,"dateline"=>$cur_time,"operator"=>$operator);
            $filter_arr = array("id"=>$rs_invoice["id"]);
            $result = $mdlInOrder->update($update_arr,$filter_arr);
            $msg = '纸质发票开票成功。';
        }
        
        //纸质发票成功记录日志;电子发票打接口开票 不管是否成功 都记录日志
        if($result){
            $opObj = app::get('ome')->model('operation_log');
            $opObj->write_log('invoice_billing@invoice', $rs_invoice['id'], $msg);
            return $rs_invoice;
        }
        
    }

    /**
     * 编辑处理函数
     * @param array $params 传入参数
     */
    public function edit($params){
        
        if(!$params["id"] || !$params["order_id"]){
            return false;
        }
        $mdlInOrder = app::get('invoice')->model('order');
        $mdlOmeOrders = app::get('ome')->model('orders');
        //获取订单信息
        $rs_orders = $mdlOmeOrders->dump(array("order_id"=>$params["order_id"]));
        if(empty($rs_orders)){
            return false;
        }
        //更新内容
        $operator = kernel::single('desktop_user')->get_id();
        $cur_time = time();
        $update_arr = array(
                "mode"=>$params["mode"],
                "tax_rate"=>$params["tax_rate"],
                "title"=>$params["title"],
                "content_id"=>$params["content_id"],
                "remarks"=>$params["remarks"],
                "operator"=>$operator,
                "update_time"=>$cur_time,
                "payee_name"=>$params["payee_name"],
                "tax_no"=>$params["tax_no"],
                "address"=>$params["address"],
                "telephone"=>$params["telephone"],
                "payee_operator"=>$params["payee_operator"],
                "bank"=>$params["bank"],
                "bank_no"=>$params["bank_no"],
                "tax_company"=>$params["tax_company"],
                "ship_tel"=>$params["ship_tel"],
                "ship_bank"=>$params["ship_bank"],
                "ship_bank_no"=>$params["ship_bank_no"],
                "ship_tax"=>$params["ship_tax"],
                "ship_area"=>$params["ship_area"],
                "ship_addr"=>$params["ship_addr"],
            );
        
        $mode = intval($params["mode"]);
        //纸质发票
        if($mode == 0){
           $update_arr["type_id"] = $params["type_id"];
           $update_arr["amount"] = $params["amount"];
           //税金始终是 订单总额*税率/100
           $update_arr["cost_tax"] = ($rs_orders["total_amount"]*$params["tax_rate"])/100;
        }
        //电子发票
        if($mode == 1){
            $update_arr["cost_tax"] = ($rs_orders["total_amount"]*$params["tax_rate"])/100;
            //电子发票开票金额(订单总额+税金)
            $update_arr["amount"] = $rs_orders["total_amount"]+$update_arr["cost_tax"];
        }
        //条件
        $filter_arr = array("id"=>$params["id"]);
        $result = $mdlInOrder->update($update_arr,$filter_arr);
        $msg_part = "编辑发票";
        
        $opObj = app::get('ome')->model('operation_log');
        if($result){
            $msg = $msg_part.'成功。';
            $opObj->write_log('invoice_edit@invoice', $params["id"], $msg);
            return true;
        }else{
            $msg = $msg_part.'失败。';
            $opObj->write_log('invoice_edit@invoice', $params["id"], $msg);
            return false;
        }
        
    }

}